package com.shelpe.services.tenant.service.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.tenant.mongomodel.AdRecommendWord;
import com.shelpe.services.tenant.mongorepository.AdRecommendWordRepository;
import com.shelpe.services.tenant.proxy.RecommendClient;
import com.shelpe.services.tenant.proxy.RecommendClient.RecommendKeywordResponse;
import com.shelpe.services.tenant.proxy.RecommendClient.RecommendWord;
import com.shelpe.services.tenant.service.RecommendWordService;

@Service
public class RecommendWordServiceImpl implements RecommendWordService{

	private static final Logger logger = LoggerFactory.getLogger(RecommendWordServiceImpl.class);
	
	@Autowired
	private AdRecommendWordRepository recommendRep;
	
	@Autowired
	private RecommendClient recommendClient;
	
	@Override
	public AdRecommendWord getRecommendWord(Long adgroupId) {
		// TODO Auto-generated method stub
		
		return recommendRep.findOne(adgroupId);
	}

	@Override
	public AdRecommendWord getRecommendWordFromProxy(String nick, Long adgroupId) {
		// TODO Auto-generated method stub
		long search = 2000;
		String pertinence = "70";
		String order = "search_volume";
		int pageSize = 200;
		int pageNo = 1;
		RecommendKeywordResponse res = recommendClient.getRecommandWordByAdgroupId(nick, adgroupId, search, pertinence, order, pageSize, pageNo);

		List<RecommendWord> reWord = null;
		
		if(res != null && res.getRes() != null && res.getRes().getPage() != null 
				&& res.getRes().getPage().getList() != null){
			reWord = res.getRes().getPage().getList().getWords();
		}else{
			if(res != null){
				logger.info("Maybe somthing is wrong, response: {}", res.getError());
			}
		}
		
		if(reWord != null){
			AdRecommendWord words = new AdRecommendWord();
			words.setAdgroupId(adgroupId);	
			words.setWord(reWord);
			return words;
		}
		
		return null;
	}

	@Override
	public void saveRecommendWord(AdRecommendWord word) {
		// TODO Auto-generated method stub
		recommendRep.save(word);
	}

}
